﻿//https://leetcode.cn/problems/longest-increasing-path-in-a-matrix/

class Solution {
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int memo[201][201];
    int m, n;

public:
    int longestIncreasingPath(vector<vector<int>>& matrix)
    {
        m = matrix.size();
        n = matrix[0].size();
        int ret = 0;

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                ret = max(ret, dfs(i, j, matrix));
            }
        }
        return ret;

    }

    int dfs(int i, int j, vector<vector<int>>& matrix)
    {
        if (memo[i][j]) return memo[i][j];
        int ret = 1;
        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y<n && matrix[x][y]>matrix[i][j])
            {
                ret = max(ret, dfs(x, y, matrix) + 1);
            }
        }
        memo[i][j] = ret;

        return ret;
    }
};